package com.bandit.utils;


import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
@SuppressWarnings("unchecked")
public class MyJSONUtils {

    /**
     * 返回jsonObj参数用fastjson
     * @param request
     * @return
     */
    public static JSONObject getRequestParamsObj(HttpServletRequest request) {
        JSONObject paramsObj = new JSONObject();
        try {
            BufferedReader streamReader = new BufferedReader( new InputStreamReader(request.getInputStream(), "UTF-8"));
            StringBuilder responseStrBuilder = new StringBuilder();
            String inputStr;
            while ((inputStr = streamReader.readLine()) != null)
                responseStrBuilder.append(inputStr);

            paramsObj = JSONObject.parseObject(responseStrBuilder.toString());

        } catch (Exception e) {
            e.printStackTrace();
        }
        return paramsObj;
    }


    /**
     * json转换成对象 jackson
     */
    public static <T> T toObject(Class classz, String jsonString) {
        ObjectMapper mapper = new ObjectMapper();
        try {
            return (T) mapper.readValue(jsonString, classz);
        } catch (IOException e) {
            System.out.println(jsonString + "转化失败");
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 对象转换成json jackson
     */
    public static String toJsonString(Object object) {
        ObjectMapper mapper = new ObjectMapper();
        try {
            return mapper.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            System.out.println(object + "转化失败");
            e.printStackTrace();
        }
        return null;
    }
}
